package gen.core.utils;

import gen.core.exceptions.GenException;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.dbutils.DbUtils;
import org.json.JSONObject;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class GenUtils {
	/**
	 * 创建数据连接。
	 * 
	 * @param theProperties
	 *            driver,url,user,password
	 * @return
	 */
	public static Connection createConnection(Properties theProperties) {
		return createConnection(theProperties, false);
	}

	/**
	 * 创建数据连接。
	 * 
	 * @param theProperties
	 *            driver,url,user,password
	 * @return
	 */
	public static Connection createConnection(Properties theProperties, boolean isAutoCommit) {
		try {
			DbUtils.loadDriver(theProperties.getProperty("driver"));
			Connection conn = DriverManager.getConnection(theProperties.getProperty("url"), theProperties);
			conn.setAutoCommit(isAutoCommit);
			return conn;
		} catch (Exception ex) {
			throw new GenException(ex, "创建数据连接时，发生异常！");
		}
	}

	/**
	 * 关闭连接。
	 * 
	 * @param conn
	 */
	public static void closeConnection(Connection conn) {
		DbUtils.rollbackAndCloseQuietly(conn);
	}

	/**
	 * 将JSON对象转化为Model对象
	 * 
	 * @param jsonobj JSON对象
	 * @param classType model的类对象
	 * @return
	 */
	public static Object json2model(JSONObject jsonobj, Class classType) {
		try {
			Object model = classType.getConstructor().newInstance();
			Map modelPropMap=BeanUtilsBean.getInstance().describe(model);
			modelPropMap.remove("class");
			
			Iterator iter = modelPropMap.keySet().iterator();
			for(;iter.hasNext();){
				String key = iter.next()+"";
				if(jsonobj.has(key)){
					modelPropMap.put(key, jsonobj.get(key));
				}
			}
			BeanUtilsBean.getInstance().populate(model, modelPropMap);
			
			return model;
		} catch (Exception ex) {
			throw new GenException(ex, "When Json -> Model, occured an Exception.");
		}
	}
}
